package com.biz.solr.utils;

import com.biz.solr.biz.conifg.BIZConfig;
import com.biz.solr.exceptions.BizSolrDeleteException;
import lombok.extern.log4j.Log4j2;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.core.query.*;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

/**
 * @ClasName SolrUtils
 * @Descripution TODO 根据业务与处理Solr
 * @Author USER
 * @Date 2022/3/24 8:59
 * @Version V1.0
 */
@Component
@Log4j2
public class BizSolrUtils {

    @Value("${spring.data.solr.host}")
    private  String solrHost;

    @Autowired
    private  SolrClient solrClient;

    @Autowired
    private SolrTemplate solrTemplate;

    public  void solrInitByCore(BIZConfig searchBIZ){
        try {
            Mono<String> result = WebClient.create(solrHost)
                    .get()
                    .uri(searchBIZ.getDataImportUrl())
                    .retrieve()
                    .bodyToMono(String.class);
        } catch (Exception e) {
            log.debug(searchBIZ.getBizCore()+"：初始化失败");
            e.printStackTrace();
            return;
        }
        log.debug(searchBIZ.getBizCore()+"：初始化");
    }


    public  void solrDeleteAllByCore(BIZConfig searchBIZ){
        try {
            solrClient.deleteByQuery(searchBIZ.getBizCore(),"*:*");
            solrClient.commit(searchBIZ.getBizCore());
        } catch (Exception e) {
            log.debug(searchBIZ.getBizCore()+"：清除全部索引失败");
            e.printStackTrace();
            return;
        }
        log.debug(searchBIZ.getBizCore()+"：清除全部索引");
    }

    public  void solrUpdateByCore(BIZConfig searchBIZ){
        Mono<String> result = null;
        try {
            result = WebClient.create(solrHost)
                    .get()
                    .uri(searchBIZ.getDataUpdateUrl())
                    .retrieve()
                    .bodyToMono(String.class);
        } catch (Exception e) {
            log.debug(searchBIZ.getBizCore()+"：更新索引失败");
            e.printStackTrace();
            return;
        }
        log.debug(searchBIZ.getBizCore()+"：更新索引");
    }


    public void solrDeleteByCoreAndHashMap(BIZConfig searchBIZ, HashMap<String, Object> wheres) {
        SimpleQuery simpleQuery = new SimpleQuery();
        Iterator<String> keyIterator = wheres.keySet().iterator();
        while (keyIterator.hasNext()){
            String whereKey = keyIterator.next();
            String solr_key = searchBIZ.getFiledName(whereKey);
            if(solr_key == null || wheres.get(whereKey) == null){
                continue;
            }
            simpleQuery.addCriteria(Criteria.where(solr_key).is(wheres.get(whereKey)));
        }
        //无参数，参数匹配不正确
        if(simpleQuery.getCriteria() == null  || CollectionUtils.isEmpty(simpleQuery.getCriteria().getPredicates()) ){
            throw new BizSolrDeleteException(searchBIZ.getBizCore()+"：参数未匹配上，请检查参数。");
        }
        try {
            solrTemplate.delete(searchBIZ.getBizCore(),simpleQuery);
            solrTemplate.commit(searchBIZ.getBizCore());
        } catch (Exception e) {
            log.debug(searchBIZ.getBizCore()+"：清除指定索引失败");
            e.printStackTrace();
            return;
        }
        log.debug(searchBIZ.getBizCore()+"：清除指定索引{"+ simpleQuery.getCriteria().getField() + simpleQuery.getCriteria().getPredicates() +"}");
    }
}
